/*
 * Copyright 2013-2014 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.report.controller;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.report.service.ConfigService;
import com.xdtech.report.util.IReportLoader;
import com.xdtech.report.util.ReportTemplateLoader;
import com.xdtech.report.vo.ConfigItem;
import com.xdtech.web.model.Pagination;

/**
 * 
 * @author max.zheng
 * @create 2015-1-15下午9:40:55
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
@RequestMapping("/readReport.do")
public class ReadReportController {
	@Autowired
	private ConfigService configService;
	@RequestMapping(params = "read")
	public ModelAndView skipConfig() {
		return new ModelAndView("report/read/readReport_ftl");
	}
	
	@RequestMapping(params = "configReportPage")
	public ModelAndView configReportPage(HttpServletRequest request,Long configId) throws Exception {
		String title = "";
		if (configId!=null) {
			ConfigItem configItem = configService.loadConfigItem(configId);
			title = configItem.getName();
			request.setAttribute("configItem",configItem );
			SAXReader reader = new SAXReader(); // User.hbm.xml表示你要解析的xml文档 
//			Document doc = reader.read(new File("G:/my-dev/git/xdtech-shop/src/test/java/pageTemplate.xml"));
			// 下面的是通过解析xml字符串的 
			Document doc = DocumentHelper.parseText(configItem.getXml()); // 将字符串转为XML 
			Element rootElement = doc.getRootElement(); 
			Element subGridDataElement = rootElement.element("datagrid");// 获取根节点datagrid
			//是否配置title
			if (null!=subGridDataElement.elementText("title")) {
				title = subGridDataElement.elementText("title");
			}
			Element searchElement = subGridDataElement.element("searchs");
			String searchId =  UUID.randomUUID().toString()+"search";
			if (null != searchElement)
			{
				StringBuffer searchHtml = createDataGridSearch(configId, searchElement, searchId);
				request.setAttribute("searchHtml", searchHtml.toString());
				request.setAttribute("searchId", searchId);
			}
			
			//获取配置列
			Element columnsElement = rootElement.element("columns");
			if (null != columnsElement&&!columnsElement.isRootElement())
			{
				String columns = createDataGridColumns(columnsElement);
				request.setAttribute("columns", columns);
			}
		}
		request.setAttribute("showReportGridId", UUID.randomUUID().toString()+"_grid");
		request.setAttribute("title", title); 
		request.setAttribute("configId", configId);
		return new ModelAndView("report/read/showReportGrid_ftl");
	}

	private String createDataGridColumns(Element columnsElement)
	{
		List<Element> columnList = columnsElement.elements();
		JSONArray columnsArray = new JSONArray();
		JSONObject columnJson = null;
		for (Element element : columnList)
		{
			columnJson = new JSONObject();
			columnJson.put("field", element.attributeValue("field"));
			columnJson.put("title", element.attributeValue("title"));
			columnJson.put("width", element.attributeValue("width")==null?80:Integer.valueOf(element.attributeValue("width")));
			if (null!=element.attributeValue("formatter")) {
				StringBuffer sbFormatter = new StringBuffer();
				sbFormatter.append("#function(value, row, index) {");
				String[] ff = element.attributeValue("formatter").split(",");
				for (int i = 0; i < ff.length; i++) {
					String kv = ff[i];
					String[] kval = kv.split("=",2);
					if (i==0) {
						sbFormatter.append("if ((value+'')=='"+kval[0]+"') { return '"+kval[1]+"'; }"); 
					}else{
						sbFormatter.append("else if ((value+'')=='"+kval[0]+"') { return '"+kval[1]+"'; }"); 
					}
				
				}
				sbFormatter.append("},#");
				columnJson.put("formatter", sbFormatter.toString());
			}
			columnsArray.add(columnJson);
		}
//				System.out.println(columnsArray.toString());
		//此方式是解决js在前端不能当作字符串处理问题
		String columns = columnsArray.toString().replace("\"#", "").replace("#\"", "");
		return columns;
	}

	private StringBuffer createDataGridSearch(Long configId, Element searchElement, String searchId)
	{
		StringBuffer searchHtml = new StringBuffer("<div id='"+searchId+"'>");
		
		Element showsearchElement = searchElement.element("showsearch");
		List<Element> itemList = showsearchElement.elements();
		System.out.println(itemList.size());
		Element hidesearchElement = searchElement.element("hidesearch");
		if (itemList.size()>0||hidesearchElement.elements().size()>0) {
			searchHtml.append("<div style=\"margin-bottom: 5px; padding-left: 5px; margin-top: 5px;\">");
			searchHtml.append("<form id='reportSearchForm"+configId+"' autocomplete='off'><table>");
			searchHtml.append("<tr>");
			//解决按enter键自动提交，导致界面报错问题 http://www.cnblogs.com/luoyanli/archive/2012/07/09/2582650.html
			searchHtml.append("<input style='display:none' />");
			createSearchItems(searchHtml, itemList);
			//搜索按钮 更多按钮 清空按钮添加
			searchHtml.append("<td><a href='javascript:void(0)' class='easyui-linkbutton' iconCls='icon-search' plain='true' onclick='reportSearch"+configId+"()'>查询</a>");
			StringBuffer hideSearchHtml = new StringBuffer();
			if (null!=hidesearchElement&&hidesearchElement.elements().size()>0) {
				//包含更多隐藏查询才显示更多按钮
				searchHtml.append("<a href='javascript:void(0)' id='moreSearchBtn"+configId+"' class='easyui-linkbutton' iconCls='layout-button-down' plain='true' onclick='moreReportSearch"+configId+"()'>更多</a>");
				hideSearchHtml.append("<tr style='display: none;' class='hiddenSearchTr"+configId+"'>");
				List<Element> hideItemList = hidesearchElement.elements();
				createSearchItems(hideSearchHtml, hideItemList);
				hideSearchHtml.append("</tr>");
			}
			searchHtml.append("<a href='javascript:void(0)' class='easyui-linkbutton' iconCls='icon-clear' plain='true' onclick='clearConfigReportSearch"+configId+"()'>清空</a>");
			searchHtml.append("</td>");
			searchHtml.append("</tr>");
			//隐藏查询从第二行开始
			searchHtml.append(hideSearchHtml);
			
			searchHtml.append("</table></form>");
			searchHtml.append("</div>");
		}
		
		
		
		
		//添加按钮
		searchHtml.append("<div style='height: auto'>")
				  .append("<a href='javascript:void(0)' class='easyui-linkbutton' iconCls='icon-export' plain='true' onclick='exportReport"+configId+"()'>导出报表</a>")
//				  .append("<a href='avascript:void(0)' class='easyui-linkbutton' iconCls='icon-large-chart' plain='true' onclick='chartReport"+configId+"()'>图表分析</a>")
				  .append("</div>");
		
		searchHtml.append("</div>");
		return searchHtml;
	}

	/**
	 * 
	 * @author max.zheng
	 * @create 2015-1-22下午11:04:09
	 * @modified by
	 * @param searchHtml
	 * @param itemList
	 */
	private void createSearchItems(StringBuffer searchHtml,
			List<Element> itemList) {
		for (Element element : itemList)
		{
			String type = element.attributeValue("type");
			searchHtml.append("<td>"+element.attributeValue("label")+"</td>");
			if ("textbox".equals(type))
			{
				searchHtml.append("<td>");
				searchHtml.append("<input name='"+element.attributeValue("name")+"' width='150px' class='easyui-validatebox easyui-textbox' />");
				searchHtml.append("</td>");
				continue;
			}
			else if ("datebox".equals(type))
			{
				searchHtml.append("<td>");
				searchHtml.append("<input name='"+element.attributeValue("name")+"' width='150px' class='easyui-validatebox easyui-datebox' />");
				searchHtml.append("</td>");
				continue;
			}
			else if ("datetimebox".equals(type))
			{
				searchHtml.append("<td>");
				searchHtml.append("<input name='"+element.attributeValue("name")+"' width='150px' class='easyui-validatebox easyui-datetimebox' />");
				searchHtml.append("</td>");
				continue;
			}
			else if ("combobox".equals(type)) {
				//<input id="77cd05da-74e8-4491-8847-47075ae30fb9" style="width:159px;" class="easyui-combobox" name="sex" data-options="url:'common.do?loadComboBox&key=SEX&value=F',required:false,valueField:'value',textField:'name',"/>
				searchHtml.append("<td>");
				searchHtml.append("<input style='width:159px;' class='easyui-combobox' name='"+element.attributeValue("name")+"' data-options=\"url:'"+element.getTextTrim()+"',required:false,valueField:'value',textField:'name',\"/>");
				searchHtml.append("</td>");
				continue;
			}
		}
	}
	
	@RequestMapping(params="loadConfigReportData")
	@ResponseBody
	public Map<String, Object> loadConfigReportData(HttpServletRequest request,Pagination pg,Long reportId) {
		Map<String, String> params = getRequestParams(request);
		Map<String, Object> results = configService.loadConfigReportPage(pg, reportId,params);	
		return results;
	}

	/**
	 * 
	 * @author max.zheng
	 * @create 2015-2-4下午11:33:30
	 * @modified by
	 * @param request
	 * @return
	 */
	private Map<String, String> getRequestParams(HttpServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Enumeration paramsMap = request.getParameterNames();
		while (paramsMap.hasMoreElements()) {
			Object object = (Object) paramsMap.nextElement();
//			System.out.println(object);
			if (StringUtils.isNotBlank(request.getParameter(object.toString()))) {
				params.put(object.toString(), request.getParameter(object.toString()));
			}
		}
		return params;
	}
	
	
	@RequestMapping(params = "chartWin")
	public ModelAndView chartWin(HttpServletRequest request,Long configId) {
		if (configId!=null) {
			ConfigItem configItem = configService.loadConfigItem(configId);
			request.setAttribute("reportChart", ReportTemplateLoader.configHighCharts(configItem)); 
		}
		request.setAttribute("chartContainer", UUID.randomUUID().toString());
		return new ModelAndView("report/read/reportChartWin_ftl");
	}
	@RequestMapping(params = "exportWin")
	public ModelAndView exportWin(HttpServletRequest request,Long configId,Long totalRecord) {
		if (configId!=null) {
			request.setAttribute("configItem", configService.loadConfigItem(configId));
			request.setAttribute("totalRecord", totalRecord);
		}
		return new ModelAndView("report/read/exportReportWin_ftl");
	}
	@RequestMapping(params="exportReport")
	public void exportReport(HttpServletRequest request,HttpServletResponse response,Long configId,String exportType) {
		try {
			ConfigItem configItem = configService.loadConfigItem(configId);
			Map<String, String> params = getRequestParams(request);
			if (StringUtils.isNotBlank(configItem.getXml()))
			{
				response.setCharacterEncoding("UTF-8");
				if (IReportLoader.PDF_TYPE.equals(exportType))
				{
					response.setContentType("application/pdf");
					String filename = System.currentTimeMillis()+".pdf";
					response.setHeader("Content-disposition", "attachment;filename=" + filename);
				}
				else if (IReportLoader.EXCEL_TYPE.equals(exportType))
				{
					response.setContentType("application/vnd.ms-excel");
					String filename = System.currentTimeMillis()+".xls";
					response.setHeader("Content-disposition", "attachment;filename=" + filename);
				}
				else if (IReportLoader.CVS_TYPE.equals(exportType))
				{
					response.setContentType("application/vnd.ms-csv");
					String filename = System.currentTimeMillis()+".csv";
					response.setHeader("Content-disposition", "attachment;filename=" + filename);
				}
				else if (IReportLoader.TXT_TYPE.equals(exportType))
				{
					response.setContentType("text/plain");
					String filename = System.currentTimeMillis()+".txt";
					response.setHeader("Content-disposition", "attachment;filename=" + filename);
				}
				else if (IReportLoader.HTML_TYPE.equals(exportType))
				{
					response.setContentType("text/html");
					String filename = System.currentTimeMillis()+".html";
					response.setHeader("Content-disposition", "attachment;filename=" + filename);
				}
				else
				{
					response.setContentType("application/pdf");
					String filename = System.currentTimeMillis()+".pdf";
					response.setHeader("Content-disposition", "attachment;filename=" + filename);
				}
				
				ServletOutputStream ouputStream = response.getOutputStream();
				ReportTemplateLoader.configIReport(configItem,exportType,params,ouputStream);
			}
			else
			{
				response.getWriter().write("模版参数不对，如：http://localhost:81/xdtech-web/readReport.do?exportReport&configId=2&exportType=excel");
			}
		} catch (Exception e) {
			System.out.println("daochu ");
		}
		
	}
}
